package com.allen.springboot.rabbitmq.consumer;

import com.allen.springboot.rabbitmq.entity.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author sesshomaru
 * @date 2020/11/16 21:06
 */
@Component
public class RabbitReceiver {

    private int a;

/*
    这个是 绑定 + 监听，如果不存在则自动创建
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue-1",
                    durable="true"),
            exchange = @Exchange(value = "exchange-1",
                    durable="true",
                    type= "topic",
                    ignoreDeclarationExceptions = "true"),
            key = "springboot.*"
    ))*/
    @RabbitListener(queues = "queue-1")
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws Exception {
        System.err.println("--------------------------------------");
        System.err.println("消费端Payload: " + message.getPayload());
        Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        //手工ACK
        channel.basicAck(deliveryTag, false);
    }


    /**
     *
     * @param order
     * @param channel
     * @param headers
     * @throws Exception
     */
/*    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue-2",
                    durable="true"),
            exchange = @Exchange(value = "exchange-2",
                    durable="true",
                    type= "topic",
                    ignoreDeclarationExceptions = "true"),
            key = "springboot.*"
    ))*/
    @RabbitListener(queues = "queue-3")
    @RabbitHandler
    public void onOrderMessage(@Payload Order order,
                               Channel channel,
                               @Headers Map<String, Object> headers) throws Exception {
        Long deliveryTag = null;
        try {
            System.err.println("------------------Consumer 消费实体--------------------" + (++a));
            System.err.println("消费端order: " + order.getId());
            deliveryTag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
            System.out.println(deliveryTag);

            // 测试 nack 且 不重回队列(实际生产环境也不要重回队列,也不要重试.) 会进入死新
            //int i = 1 / 0;

        } catch (Exception e) {
            System.out.println("出错了.....");
            channel.basicNack(deliveryTag, false,false);
            return;
        }
        System.out.println(11111);
        channel.basicAck(deliveryTag, false);
    }
}
